package com.dc.task;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Component
public class WebsocketClient {

    //接收路径
    private String ws = "";

    public WebSocketClient client;

    private Timer timer = new Timer();

    //存放所有url的client对象
    private static ConcurrentMap<String, WebSocketClient> cumap = new ConcurrentHashMap<>();

    //长连接心跳
    private static ConcurrentMap<String, WebSocketClient> LongConnectionMap = new ConcurrentHashMap<>();

    /**
     * webSocket客户端初始化连接
     *
     * @param url
     * @param type
     * @return
     */
    public WebSocketClient initFactory(String url, int type) { // url:ws地址    type 0:普通 1:长连接心跳
        try {
            ws = url;
            client = new WebSocketClient(new URI(url), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("握手成功");
                }

                @Override
                public void onMessage(String msg) {
                    log.info("收到消息==========" + msg);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    cumap.remove(ws);
                    log.info("链接已关闭");
                }

                @Override
                public void onError(Exception e) {
                    cumap.remove(ws);
                    e.printStackTrace();
                    log.info("发生错误已关闭");
                }
            };
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (cumap.containsKey(url)) {
            return cumap.get(url);
        }
        client.connect();
        int i = 0;
        while (i < 100 && !client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
            try {
                i++;
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("正在连接...");
        }
        cumap.put(ws, this.client);

        if (1 == type) { // type 0:普通 1:长连接心跳
            LongConnectionMap.put(ws, this.client);
            this.heartBeat(url);
        }
        return client;
    }

    /**
     * 长连接心跳检测重连
     *
     * @param url
     */
    public void heartBeat(String url) {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("websocket心跳:{}", url);
                WebSocketClient webSocketClient = LongConnectionMap.get(url);
                boolean open = webSocketClient.isOpen();
                if (!open) {
                    log.info("正在重连:{}", url);
                    //重连
                    webSocketClient.reconnect();
                }
            }
        }, 60000, 60000); //在60秒后执行此任务,每次间隔60秒执行一次
    }
}

